package com.win.controller.mysql;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.win.pojo.vo.Useruploadlog;
import com.win.service.UseruploadlogService;
import com.win.utils.Result;
import com.win.utils.ResultCodeEnum;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("logs")
@CrossOrigin
@Slf4j
public class LogController {
    @Autowired
    private UseruploadlogService logService;

    @GetMapping("/{username}")
    public Result Log(@PathVariable String username){
        if (!(username.equals("admin"))){
            return Result.build(null, ResultCodeEnum.NOT_PERMISSION);
        }
        Result result = logService.getLog();
        return result;
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        log.info("开始导出文件信息");

        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<Useruploadlog> list = logService.list();

        //将查询到的所有日志信息通过ExcelWriter中的write方法写出
        writer.write(list,true);

        //设置响应头的信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode("uploadLog","UTF-8") + ".xlsx");

        //获取相应输出流对象
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.flush();
        outputStream.close();
    }


}
